package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.forms.ApproverOrderForm;
import com.scalar.chiptrack.users.User;


/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.1.1.1 $ $Date: 2006/12/11 23:43:17 $
 */

public final class ApproveOnlineOrderAction extends ChipTrackAction {

    private static final String ACTION_NAME = "/approveOnlineOrder.do" ;  // Added by Basha (08/08/2003)

    // ----------------------------------------------------- Instance Variables
   

    // --------------------------------------------------------- Public Methods


    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception Exception if business logic throws an exception
     */
    public ActionForward execute(ActionMapping mapping,
				 ActionForm form,
				 HttpServletRequest request,
				 HttpServletResponse response)
	throws Exception {
        
            // Extract attributes and parameters we will need
            ApproverOrderForm subform = (ApproverOrderForm) form;
            String action = request.getParameter("action");
                               
             //Get the session, to retrieve the values
	         HttpSession session = request.getSession();


             User user = (User)session.getAttribute (SessionKeys.USER_KEY);
             // Added by Basha (08/08/2003)
             if (user == null)
             {
                session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
                return (mapping.findForward ("login"));
             }
            // Added by Basha (08/08/2003)



             //Put all the errors/messages
             HashMap errors = new HashMap();
            
            if((action != null) && (action.equals("ApproveOnlineOrder")))
            {
                //Do the code for approve
                int onlineOrderId = subform.getSalesOrderId();
                int salesOrderId = -1;
                DBTransaction dbTransaction = null;
                boolean success = false;
                
                try {                       
                   //Begine Transaction
                   dbTransaction = DBTransaction.getInstance();
                   dbTransaction.begin();
                   
                   //Get the lineItems..
                   String[] lineItemIds = request.getParameterValues("lineItemId");
                   String[] quantity = request.getParameterValues("quantity");
                   String[] unitPrice = request.getParameterValues("unitPrice");
                   
                   //Save the salesOrder details & get the salesOrderId
                   salesOrderId = SalesOrderDAO.saveOnlineSalesOrder(dbTransaction, onlineOrderId, 
                                            user.getUserId());
                       
                   //Save the LineItems..
                   ArrayList lineItems = SalesOrderDAO.insertOnlineLineItems(dbTransaction,onlineOrderId,lineItemIds,
                                                quantity, unitPrice, user.getUserId());
                        
                   //Check For the finance limits, 1 for sample
                   SalesOrderDAO.checkForLimits(dbTransaction,lineItems,salesOrderId,
                                    subform.getSalesOrder().getCustomerId(),user.getUserId(),1);
                              
                   success = true;
                   
                   request.setAttribute("salesOrderId",Integer.toString(salesOrderId));
                   
                }
                catch (ScalarException se) {
                    // Exception while updating user profile
                    // log it
                    se.printStackTrace();
                }
                finally {
                   // Rollback or Commit the Transaction
                   if (success == true) {
                        dbTransaction.commit();
                        
                        errors.put("SalesOrder = " + (String)request.getAttribute("salesOrderId"), "Approved Successfully");
                        errors.put("View/Print ","Click here to <a href='javascript:openSalesOrder();'> view/print </a>Sales Order Details");
                        
                        try {
                            //Update the alarm with comments
                            SalesDAO.updateAlarm(subform.getApproverComments(),salesOrderId,true,user);   
                            errors.put("Email ", " has been send to all approvers");
                        } catch(Exception ex) {
                            errors.put("Email ", " Exception occured in sending email to all approvers");
                        }
                            
                   }
                   else {
                        dbTransaction.rollback();
                        
                        errors.put("SalesOrder = " + (String)request.getAttribute("salesOrderId"), "Rejected Successfully");
                    }
                }
                             
                if(!errors.isEmpty()) 
                      request.setAttribute(SessionKeys.MESSAGES, errors);
                
                return (mapping.findForward("success"));
                
            }
            else
            if((action != null) && (action.equals("RejectOnlineOrder")))
            {
                //Do the code for reject
                int salesOrderId = subform.getSalesOrderId();
                
                try {
                    //Update the hold table, with userId, isApprove = false, 
                    SalesDAO.updateHoldTable(null,salesOrderId, false,user);
                    
                    errors.put("SalesOrder = " + (String)request.getAttribute("salesOrderId"), "Rejected Successfully");
                    errors.put("View/Print ","Click here to <a href='javascript:openSalesOrder();'> view/print </a>Sales Order Details");
                    
                    try {
                        //Update the alarm with comments
                        SalesDAO.updateAlarm(subform.getApproverComments(),salesOrderId,false,user);
                        SalesOrderDAO.sendMailToCustomer(salesOrderId); // If the order is approved then it needs to send to customer
                        errors.put("Email ", " has been send to all approvers");
                    } catch (Exception exc) {
                        errors.put("Email ", " Exception occured in sending email to all approvers");
                    }
                                        
                    
                } catch(Exception ex) {                    
                    errors.put("SalesOrder", "Problem in rejecting the salesOrder");
                }
                
                if(!errors.isEmpty()) 
                      request.setAttribute(SessionKeys.MESSAGES, errors);
                
                return (mapping.findForward("success"));                
            }
            else
            if(request.getParameter("salesOrderId") != null) {
                
                //Get the salesOrderDetails
                SalesOrder salesOrder = SalesOrderDAO.loadOnlineOrder(
                            request.getParameter("salesOrderId"));
                            
                //Set the salesOrder into FormBean
                subform.setSalesOrder(salesOrder);
                subform.setSalesOrderId(salesOrder.getSalesOrderId());
                
                //Set the current order lineItems
                request.setAttribute("presentLineItems",
                        SalesOrderDAO.loadOnlineOrderLineItems(salesOrder.getSalesOrderId()));
            
                //return to the approver page, where approver can approve/reject
                return (mapping.findForward("salesOrder"));
                
            }
            
            
            return (mapping.findForward("success"));
    }
    
               
}
